import axios from "axios";
import { useUserStore } from "@/stores/user.js";
import router from "@/router";
import { ElMessage } from "element-plus";
const baseUrl = "http://big-event-vue-api-t.itheima.net";
const instance = axios.create({
  baseURL: baseUrl,
  timeout: 5000,
});
// 请求拦截
instance.interceptors.request.use(
  (config) => {
    const useStore = useUserStore();
    if (useStore.token) {
      config.headers["Authorization"] = useStore.token;
    }
    return config;
  },
  (err) => {
    Promise.reject(err);
  }
);
// 响应拦截
instance.interceptors.response.use(
  (res) => {
    if (res.data.code === 0) {
      return res.data;
    }
    console.log(res, "res");
    ElMessage.error(res.data.message || "服务异常");
    return Promise.reject(res.data);
  },
  (Error) => {
    // 401错误
    if (Error.response?.status === 401) {
      router.push("/login");
      ElMessage.error("登录失效，请重新登录");
    }
    // 错误默认情况
    ElMessage.error(Error.response.data.message || "服务异常");
    // ElMessage.error("服务异常");
    return Promise.reject(Error);
  }
);
export default instance;
export { baseUrl };
